﻿using Esosi.Entity;
using Esosi.Register.Hospital.Models;
using Esosi.Repository;
using Esosi.Repository.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Esosi.Register.Hospital.HospitalPolicy
{
    /// <summary>
    /// 分类按比例支付
    /// </summary>
    public class SortPolicyStrategy : PolicyStrategyBase
    {
        public SortPolicyStrategy(GmChargePolicy gmChargePolicy) : base(gmChargePolicy)
        {
        }

        public override PaySum ApplyPolicy(RegisterHospitalTpi tpi)
        {
            //根据费用汇总分类金额
            var sortSums = tpi.FeeItems.
                GroupBy(p => new { p.IApplyStatus, p.IFeeTypeCode, p.PolicyFeeTypeCode, p.ReckoningTypeCode }).
                Select(g => new SortSum
                {
                    IApplyStatus = g.Key.IApplyStatus,
                    IFeeTypeCode = g.Key.IFeeTypeCode,
                    PolicyFeeTypeCode = g.Key.PolicyFeeTypeCode,
                    ReckoningTypeCode = g.Key.ReckoningTypeCode,
                    FeeAmount = g.Sum(p => p.Summary)
                }
            ).ToList();

            var paySum = new PaySum
            {
                InvoicePayMode = (InvoicePayMode)_gmChargePolicy.InvoicePayModeCode
            };

            sortSums.ForEach(p =>
           {
               var chargePolicyDetail = _gmChargePolicy.GmChargePolicyDetails.
                       FirstOrDefault(x => x.PolicyFeeTypeCode == p.PolicyFeeTypeCode);
               var policyFeeSum = p.FeeAmount * chargePolicyDetail.Percent / 100 + chargePolicyDetail.Ration;
               p.FeeAmount = Math.Round(policyFeeSum, 2, MidpointRounding.AwayFromZero);
               paySum.SortSums.Add(p);
           });

            paySum.FeeSum = paySum.SortSums.Sum(p => p.FeeAmount);

            return paySum;
        }
    }
}